package com.jiawentan.lib_demo;
import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class First_JDBC {
    public static void main(String[] args) {
        try {
            MysqlDataSource dataSource = new MysqlDataSource();
            dataSource.setServerName("127.0.0.1");
            dataSource.setPort(3306);
            dataSource.setUser("root");
            dataSource.setPassword("123456");
            dataSource.setDatabaseName("java45_12_7");
            dataSource.setCharacterEncoding("utf-8");
            dataSource.setUseSSL(false);
            dataSource.setServerTimezone("Asia/Shanghai");
            Connection c = null;
            try {
                c = dataSource.getConnection();
                String sql="select id,name from student where id>5 order by id desc";
                PreparedStatement ps=null;
                try{
                    ps=c.prepareStatement(sql);
                    ResultSet rs=null;
                    try{
                        rs=ps.executeQuery();
                        while(rs.next()){
                            int id=rs.getInt("id");
                            String name=rs.getString("name");
                            System.out.println("id = "+id+",name = "+name);
                        }
                    }finally {
                        if(rs!=null){
                            rs.close();
                        }
                    }
                }finally {
                    if(ps!=null){
                        ps.close();
                    }
                }
            } finally {
                if (c != null) {
                    c.close();
                }
            }
        } catch (SQLException exc) {
            throw new RuntimeException(exc);
        }
    }
}
